package xiancheng.ticket;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Mr.ma
 * @since 2022/11/1 20:19
 *
 * 使用手动锁解决线程安全问题
 **/
public class TestLock {
    public static void main(String[] args) {
        TestRunnable04 sellingTickets = new TestRunnable04();
        Thread thread1 = new Thread(sellingTickets, "窗口1");
        Thread thread2 = new Thread(sellingTickets, "窗口2");
        Thread thread3 = new Thread(sellingTickets, "窗口3");
        Thread thread4 = new Thread(sellingTickets, "窗口4");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}

class TestRunnable04 implements Runnable {
    private Integer ticket = 100;
    @Override
    public void run() {
        Lock reentrantLock = new ReentrantLock();
        while (true) {
            reentrantLock.lock();
            try {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "卖了一张票,剩余" + --ticket);
                } else {
                    break;
                }
            }finally {
                reentrantLock.unlock();
            }
        }
    }
}